package com.yeyks.commonReference.append.activity.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yeyks.activity.dal.domain.ActivityNoviceTask;
import com.yeyks.activity.param.ActivityNodeUserRecordSaveByActivityParam;
import com.yeyks.activity.service.ActivityNodeUserRecordService;
import com.yeyks.activity.service.ActivityNoviceTaskService;
import com.yeyks.common.constants.MessageTemplate;
import com.yeyks.common.constants.consumer.UserInviteRelationTypeConstant;
import com.yeyks.common.em.UserBillType;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.param.consumer.UserIdParam;
import com.yeyks.common.utils.FormatUtils;
import com.yeyks.common.utils.RedisUtil;
import com.yeyks.commonReference.append.activity.ActivityNewUserTaskService;
import com.yeyks.commonReference.pojo.param.activity.NewUser.ActivityNewUserTaskReceiveParam;
import com.yeyks.commonReference.service.activity.ActivityBaseService;
import com.yeyks.commonReference.service.consumer.UserCouponInfoService;
import com.yeyks.consumer.dal.domain.MessageNotice;
import com.yeyks.consumer.service.MessageNoticeService;
import com.yeyks.consumer.service.UserAccountOverviewService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class ActivityNewUserTaskServiceImpl implements ActivityNewUserTaskService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ActivityBaseService activityBaseService;
    @Autowired
    private ActivityNoviceTaskService activityNoviceTaskService;
    @Autowired
    private UserCouponInfoService userCouponInfoService;
    @Autowired
    private UserAccountOverviewService userAccountOverviewService;
    @Autowired
    private MessageNoticeService messageNoticeService;
    @Autowired
    private ActivityNodeUserRecordService activityNodeUserRecordService;

    //任务是否截止
    @Override
    public void checkEnd() {
        activityBaseService.checkActivityEndDate(activity_code);
    }

    //创建任务
    @Override
    public void createTask(Integer userId) {
        try {
            checkEnd();
        } catch (Exception e) {
            return;
        }
        try {
            ArrayList<ActivityNoviceTask> activityNoviceTasks = new ArrayList<>();
            activityNoviceTasks.add(
                    new ActivityNoviceTask()
                            .setUserId(userId)
                            .setPrice(1000)
                            .setType(1)
                            .setTitle("完成新手引导")
                            .setReward("奖励10元酒店红包")
                            .setDescription("活动期间完成新手引导任务，得10元优惠券")
                            .setStatusa(1)
            );
            activityNoviceTasks.add(
                    new ActivityNoviceTask()
                            .setUserId(userId)
                            .setPrice(300)
                            .setType(2)
                            .setTitle("完成第一笔订单")
                            .setReward("奖励3元现金")
                            .setDescription("活动期间下单，订单完成后即可领取现金")
                            .setStatusa(1)
            );
            activityNoviceTasks.add(
                    new ActivityNoviceTask()
                            .setUserId(userId)
                            .setPrice(300)
                            .setType(3)
                            .setTitle("完成一笔200元订")
                            .setReward("奖励3元现金")
                            .setDescription("活动期间下单，订单金额达到200元，完成后即可领取现金")
                            .setStatusa(1)
            );
            activityNoviceTasks.add(
                    new ActivityNoviceTask()
                            .setUserId(userId)
                            .setPrice(500)
                            .setType(4)
                            .setTitle("完成一笔300元")
                            .setReward("奖励5元现金")
                            .setDescription("活动期间下单，订单金额达到300元，完成后即可领取现金")
                            .setStatusa(1)
            );
            activityNoviceTaskService.saveBatch(activityNoviceTasks);
        } catch (Exception e) {
            log.error("创建新手任务失败,用户id：{}", userId);
        }
    }

    //任务列表
    @Override
    public List<ActivityNoviceTask> list(UserIdParam param) {
        List<ActivityNoviceTask> list = activityNoviceTaskService.list(
                new QueryWrapper<ActivityNoviceTask>()
                        .eq(ActivityNoviceTask.USER_ID, param.getUserId())
                        .orderByAsc(ActivityNoviceTask.TYPE)
        );
        return list;
    }

    //完成新手引导
    @Override
    public void finishOne(UserIdParam param) {
        boolean update = activityNoviceTaskService.update(
                new UpdateWrapper<ActivityNoviceTask>()
                        .set(ActivityNoviceTask.STATUSA, 2)
                        .eq(ActivityNoviceTask.USER_ID, param.getUserId())
                        .eq(ActivityNoviceTask.STATUSA, 1)
                        .eq(ActivityNoviceTask.TYPE, 1)
        );
        if (!update) {
            throw new ServiceException("完成引导失败");
        }
        //存储统计
        activityNodeUserRecordService.saveByActivity(new ActivityNodeUserRecordSaveByActivityParam().setActivityCode(activity_code).setNode("finish_one").setUserId(String.valueOf(param.getUserId())));
    }

    //领取奖品
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActivityNoviceTask receive(ActivityNewUserTaskReceiveParam param) {
        return redisUtil.runWithLock("lock:acticity:new:user:task:" + param.getUserId(), () -> {
            //查询任务
            ActivityNoviceTask activityNoviceTask = activityNoviceTaskService.getOne(
                    new QueryWrapper<ActivityNoviceTask>()
                            .eq(ActivityNoviceTask.ID, param.getTaskId())
                            .eq(ActivityNoviceTask.USER_ID, param.getUserId())
                            .last("limit 1")
            );
            if (Objects.equals(activityNoviceTask.getStatusa(), 2)) {
                //按分类发放奖品
                switch (activityNoviceTask.getType()) {
                    case 1:
                        userCouponInfoService.giveTypeCoupon(param.getUserId(), 12);
                        //存储统计
                        activityNodeUserRecordService.saveByActivity(new ActivityNodeUserRecordSaveByActivityParam().setActivityCode(activity_code).setNode("over_one").setUserId(String.valueOf(param.getUserId())));
                        break;
                    case 2:
                        addAmount(param.getUserId(), 300);
                        //存储统计
                        activityNodeUserRecordService.saveByActivity(new ActivityNodeUserRecordSaveByActivityParam().setActivityCode(activity_code).setNode("over_two").setUserId(String.valueOf(param.getUserId())));
                        break;
                    case 3:
                        addAmount(param.getUserId(), 300);
                        //存储统计
                        activityNodeUserRecordService.saveByActivity(new ActivityNodeUserRecordSaveByActivityParam().setActivityCode(activity_code).setNode("over_three").setUserId(String.valueOf(param.getUserId())));
                        break;
                    case 4:
                        addAmount(param.getUserId(), 500);
                        //存储统计
                        activityNodeUserRecordService.saveByActivity(new ActivityNodeUserRecordSaveByActivityParam().setActivityCode(activity_code).setNode("over_four").setUserId(String.valueOf(param.getUserId())));
                        break;
                    default:
                        throw new ServiceException("未知任务");
                }
                //更新任务状态
                boolean update = activityNoviceTaskService.update(
                        new UpdateWrapper<ActivityNoviceTask>()
                                .set(ActivityNoviceTask.STATUSA, 3)
                                .eq(ActivityNoviceTask.ID, activityNoviceTask.getId())
                );
                if (!update) {
                    throw new ServiceException("服务器正忙，请重试");
                }
            } else if (Objects.equals(activityNoviceTask.getStatusa(), 1)) {
                throw new ServiceException("任务未完成");
            } else {
                throw new ServiceException("奖品已领取");
            }
            return activityNoviceTask;
        });
    }

    private void addAmount(Integer userId, Integer amount) {
        //添加佣金
        userAccountOverviewService.addAmount(amount, userId, UserBillType.NEW_USER_TASK.value(), UserBillType.NEW_USER_TASK.desc(), UserInviteRelationTypeConstant.NEW_USER_TASK);
        //添加佣金记录
        Map<String, Object> map = new HashMap<>();
        map.put("amount", FormatUtils.fenToYuan(amount));
        messageNoticeService.saveMessageNoticeSimple(MessageTemplate.NEW_USER_TASK_AMOUNT, map, userId, MessageNotice.Type.NEW_USER_TASK.value());
    }

}
